package com.bmps.springcloud.insuredmicroservice.service.accept;

import com.bmps.springcloud.common.response.TaskResponseModel;
import com.bmps.springcloud.common.utils.IDCardCheck;
import com.bmps.springcloud.insuredmicroservice.constant.accept.AcceptConstant;
import com.bmps.springcloud.insuredmicroservice.model.accept.PersonModel;
import com.bmps.springcloud.insuredmicroservice.service.RedisService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @author lyw
 * @date 2019/07/24
 */
@Service
public class AcceptBlackCustomerServiceImpl implements AcceptBlackCustomerService {

    private static Logger logger = LoggerFactory.getLogger(AcceptBlackCustomerServiceImpl.class);

    private final RedisService redisService;

    public AcceptBlackCustomerServiceImpl(RedisService redisService) {
        this.redisService = redisService;
    }

    @Override
    public TaskResponseModel checkBlackCustomer(String key, PersonModel personModel) {
        StringBuilder sb = new StringBuilder();
        sb.append(AcceptConstant.REDIS_PREFIX_D001)
                .append("|")
                .append("blacklist")
                .append("|")
                .append(DigestUtils.md5DigestAsHex(personModel.getName().getBytes()));
        logger.info("【缓存黑名单KEY】" + sb.toString());
        Set<?> members;
        try {
            members = redisService.members(sb.toString());
        } catch (Exception e) {
            logger.error("业务逻辑黑名单任务校验失败：" + e.getMessage());
            TaskResponseModel taskResponseModel = new TaskResponseModel();
            taskResponseModel.setKey(AcceptConstant.TASK_ERROR);
            taskResponseModel.setResultMessage("业务逻辑黑名单任务校验失败:" + AcceptConstant.RESULT_FAIL_MESSAGE);
            return taskResponseModel;
        }
        List<PersonModel> personModelList = (members == null) ? new ArrayList<>(0) : getPerson(members);
        if (CollectionUtils.isEmpty(personModelList)) {
            return createTaskResponseModel(key);
        }
        TaskResponseModel taskResponseModel = isExistBlackName(personModelList, personModel);
        taskResponseModel.setKey(key);

        logger.info("【业务逻辑校验结果】" + taskResponseModel.toString());
        return taskResponseModel;
    }

    private TaskResponseModel createTaskResponseModel(String key) {
        TaskResponseModel taskResponseModel = new TaskResponseModel();
        taskResponseModel.setKey(key);
        taskResponseModel.setResultCode(AcceptConstant.RESULT_SUCCESS_CODE);
        taskResponseModel.setResultMessage(AcceptConstant.RESULT_SUCCESS_MESSAGE);
        return taskResponseModel;
    }

    private TaskResponseModel isExistBlackName(List<PersonModel> personModelList, PersonModel personModel) {
        TaskResponseModel taskResponseModel = new TaskResponseModel();
//        boolean exist = personModelList.stream().anyMatch(p ->
//                StringUtils.equals(p.getSex(), personModel.getSex())
//                        && StringUtils.equals(p.getBirthday(), personModel.getBirthday())
//                        && StringUtils.equals(p.getIdType(), personModel.getIdType())
//                        && equalsIdNo(p, personModel));
        boolean exist = personModelList.stream().anyMatch(p -> checkIdentityElement(p, personModel));
        if (exist) {
            taskResponseModel.setResultCode(AcceptConstant.RESULT_FAIL_CODE);
            taskResponseModel.setResultMessage(AcceptConstant.BLACK_LIST_SYSTEM_MESSAGE);
        } else {
            taskResponseModel.setResultCode(AcceptConstant.RESULT_SUCCESS_CODE);
            taskResponseModel.setResultMessage(AcceptConstant.RESULT_SUCCESS_MESSAGE);
        }
        return taskResponseModel;
    }

    private boolean equalsIdNo(PersonModel person, PersonModel personModel) {
        if (StringUtils.isEmpty(person.getIdNo())) {
            return false;
        }
        if (StringUtils.equals(AcceptConstant.CREDENTIALS_IDNO, person.getIdType())
                && IDCardCheck.checkIDCard(person.getIdNo())) {
            return StringUtils.equals(IDCardCheck.turnTo18(person.getIdNo()), IDCardCheck.turnTo18(personModel.getIdNo()));
        } else {
            // 非有效身份证直接比较
            return StringUtils.equals(personModel.getIdNo(), person.getIdNo());
        }
    }

    private List<PersonModel> getPerson(Set<?> personList) {
        List<PersonModel> personModelList = new ArrayList<>();
        //list集合：姓名|性别|生日|证件类型|证件号码
        for (Object s : personList) {
            String[] array = s.toString().split("\\|");
            PersonModel personModel = new PersonModel();
            switch (array.length) {
                case 5: {
                    personModel.setIdNo(array[4]);
                    personModel.setIdType(array[3]);
                    personModel.setBirthday(array[2]);
                    personModel.setSex(array[1]);
                    personModel.setName(array[0]);
                    break;
                }
                case 4: {
                    personModel.setIdType(array[3]);
                    personModel.setBirthday(array[2]);
                    personModel.setSex(array[1]);
                    personModel.setName(array[0]);
                    break;
                }
                case 3: {
                    personModel.setBirthday(array[2]);
                    personModel.setSex(array[1]);
                    personModel.setName(array[0]);
                    break;
                }
                case 2: {
                    personModel.setSex(array[1]);
                    personModel.setName(array[0]);
                    break;
                }
                case 1: {
                    personModel.setName(array[0]);
                    break;
                }
                default:
            }
            personModelList.add(personModel);
        }
        return personModelList;
    }

    private boolean checkIdentityElement(PersonModel target, PersonModel source) {
        //性别
        if (StringUtils.isNotBlank(source.getSex()) && StringUtils.isNotBlank(target.getSex())) {
            if (!StringUtils.equals(target.getSex(), source.getSex())) {
                return false;
            }
        }
        //生日
        if (StringUtils.isNotBlank(source.getBirthday()) && StringUtils.isNotBlank(target.getBirthday())) {
            if (!StringUtils.equals(target.getBirthday(), source.getBirthday())) {
                return false;
            }
        }
        //证件类型
        if (StringUtils.isNotBlank(source.getIdType()) && StringUtils.isNotBlank(target.getIdType())) {
            if (!StringUtils.equals(target.getIdType(), source.getIdType())) {
                return false;
            }
        }
        //证件号
        if (StringUtils.isNotBlank(source.getIdNo()) && StringUtils.isNotBlank(target.getIdNo())) {
            if (!equalsIdNo(target, source)) {
                return false;
            }
        }
        return true;
    }
}
